import React, { useState, useEffect, useCallback } from "react";
import { Button, Tag, Input, List, message, Modal, Spin, notification } from "antd"; // 添加 Modal, notification
import {
  HeartOutlined,
  HeartFilled,
  StarOutlined,
  StarFilled,
} from "@ant-design/icons";
import MDEditor from "@uiw/react-md-editor";
import { MdEditor, MdPreview, MdCatalog } from "md-editor-rt";
import {
  fetchSeedDetail,
  likeSeed,
  unlikeSeed,
  collectSeed,
  uncollectSeed,
  postComment,
  fetchComments,
  deleteComment,
} from "../api/SeedApi";
import "./SeedDetail.css";
import EmojiSelector from "../components/EmojiSelector"; // 导入表情选择组件

function SeedDetail({ id,admin=false, visible, onClose }) {
  const [seedDetail, setSeedDetail] = useState(null);
  const [liked, setLiked] = useState(false);
  const [favorited, setFavorited] = useState(false);
  const [comments, setComments] = useState([]);
  const [newComment, setNewComment] = useState("");
  const [replyTo, setReplyTo] = useState(null);
  const [loading, setLoading] = useState(false);

  // 获取种子详情
  useEffect(() => {
    if (id && visible) {
      const fetchDetail = async () => {
        setLoading(true);
        try {
          const data = await fetchSeedDetail(id);
          // 将 data.tags 字符串转换为数组
          if (data.tags && typeof data.tags === "string") {
            data.tags = data.tags.split(",").map((tag) => ({
              label: tag.trim(),
              value: tag.trim(),
            }));
          }
          setSeedDetail(data);
          setLiked(data.liked || false);
          setFavorited(data.favorited || false);
          // 单独请求评论
          const commentData = await fetchComments(id);
          setComments(commentData || []);
        } catch (error) {
          console.error("加载种子详情失败:", error);
          message.error("加载详情失败");
        } finally {
          setLoading(false);
        }
      };
      fetchDetail();
    }
  }, [id, visible]);

  // 清理状态
  useEffect(() => {
    if (!visible) {
      setSeedDetail(null);
      setNewComment("");
      setReplyTo(null);
    }
  }, [visible]);

  // 获取登录的用户名
  const userId = localStorage.getItem("userId");

  // 点赞功能
  const handleLike = async () => {
    if (!userId) {
      message.warning("请先登录后再点赞！");
      return;
    }

    try {
      if (liked) {
        const response = await unlikeSeed(id, userId); // 传递种子 ID 和用户名
        setLiked(!liked); // 更新点赞状态
        message.success(response.message || "取消点赞成功！");
      } else {
        const response = await likeSeed(id, userId); // 传递种子 ID 和用户名
        setLiked(!liked); // 更新点赞状态
        message.success(response.message || "点赞成功！");
      }
    } catch (error) {
      message.error("点赞失败，请稍后重试！");
    }
  };

  // 收藏功能
  const handleCollect = async () => {
    if (!userId) {
      message.warning("请先登录后再收藏！");
      return;
    }

    try {
      if (favorited) {
        const response = await uncollectSeed(id, userId); // 传递种子 ID 和用户名
        setFavorited(!favorited); // 更新收藏状态
        message.success(response.message || "收藏成功！");
      } else {
        const response = await collectSeed(id, userId); // 传递种子 ID 和用户名
        setFavorited(!favorited); // 更新收藏状态
        message.success(response.message || "收藏成功！");
      }
    } catch (error) {
      message.error("收藏失败，请稍后重试！");
    }
  };

  // 提交评论
  const handleCommentSubmit = async () => {
    if (!userId) {
      message.warning("请先登录后再发表评论！");
      return;
    }
    if (!newComment.trim()) {
      message.warning("评论内容不能为空！");
      return;
    }
    try {
      // 使用正则表达式匹配并替换表情 URL
      let processedComment = newComment.replace(
        /!\[(.*?)\]\((.*?)\)/g,
        (match, p1, p2) => {
          if (!p2.startsWith("http")) {
            return `![${p1}](http://47.93.133.173:9000/bt7274/smilies/${p2})`;
          }
          return match;
        }
      );
      //处理换行符
      processedComment = processedComment.replace(/\n/g, "<br />");

      const response = await postComment(id, userId, processedComment, replyTo);
      setComments([...comments, response.data]);
      setNewComment("");
      setReplyTo(null); // 提交后重置回复对象
      message.success(response.message || "评论成功！");
    } catch (error) {
      message.error("评论失败，请稍后重试！");
    }
  };

  //删除评论
  const handleDeleteComment = async (seedId, commentId) => {
    try {
      const response = await deleteComment(seedId, commentId);
      if (response.success) {
        setComments(comments.filter(comment => comment.id !== commentId));
        console.log('评论删除成功'); // 调试信息
        notification.success({
          message: '删除成功',
          description: '评论删除成功',
          placement: 'topRight',
        });
      } else {
        message.error(response.msg);
      }
    } catch (error) {
      message.error('删除评论失败');
    }
  };
  const handleInsertEmoji = (emojiText) => {
    setNewComment((prevComment) => prevComment + emojiText);
  };

  return (
    <Modal
      title={seedDetail?.title || "种子详情"}
      visible={visible}
      onCancel={onClose}
      footer={null}
      width="80%"
      className="seed-detail-modal"
      style={{
        top: "5vh",
        paddingBottom: 0,
      }}
    >
      <Spin spinning={loading}>
        {seedDetail && (
          <div className="seed-detail-container">
            <div className="seed-category-tags">
              <Tag color="#ff6699" style={{ marginRight: "12px" }}>
                {seedDetail.category}
              </Tag>
              {seedDetail.tags.map((tag, index) => (
                <Tag key={index} color="#2db7f5">
                  {tag.label}
                </Tag>
              ))}
            </div>

            <div className="seed-description">
              <MdPreview
                id="preview-only"
                value={seedDetail.description}
                style={{
                  padding: "16px",
                  background: "transparent",
                  border: "none",
                }}
              />
            </div>

            <div className="seed-actions">
              <Button
                type="primary"
                href={seedDetail.downloadLink}
                target="_blank"
              >
                下载种子
              </Button>
              <Button
                type="text"
                icon={
                  liked ? (
                    <HeartFilled style={{ color: "red" }} />
                  ) : (
                    <HeartOutlined />
                  )
                }
                onClick={handleLike}
              >
                <span className={`like-count ${liked ? "animate" : ""}`}>
                  {seedDetail.likes}
                </span>
              </Button>
              <Button
                type="text"
                icon={
                  favorited ? (
                    <StarFilled style={{ color: "gold" }} />
                  ) : (
                    <StarOutlined />
                  )
                }
                onClick={handleCollect}
              >
                {favorited ? "已收藏" : "收藏"}
              </Button>
            </div>

            <div className="seed-comments">
              <h3>评论</h3>
              <List
                dataSource={comments}
                renderItem={(comment, index) => (
                  admin===false?
                  <List.Item
                    key={index}
                    onClick={() => setReplyTo(comment.username)}
                  >
                    <div>
                      <b>{comment.username}：</b>
                      {comment.replyTo && (
                        <span style={{ color: "#888", marginLeft: 8 }}>
                          回复 {comment.replyTo}
                        </span>
                      )}
                      {/* 使用 MDEditor.Markdown 组件显示 Markdown 内容 */}
                      <MDEditor.Markdown
                        source={comment.content}
                        style={{
                          display: "inline",
                          padding: 0,
                          background: "transparent",
                          border: "none",
                        }}
                      />
                    </div>
                    </List.Item>
                    :
                    <List.Item
                    key={index}
                    onClick={() => setReplyTo(comment.username)}
                  >
                    <div>
                      <b>{comment.username}</b>
                      {comment.replyTo && (
                        <span style={{ color: "#888", marginLeft: 8 }}>
                          回复 {comment.replyTo}
                        </span>
                      )}
                        ：{comment.content}
                        <Button 
                          type="link" 
                          danger 
                          onClick={() => handleDeleteComment(seedDetail.torrentId,comment.id)} // Pass the comment ID to delete
                          style={{ marginLeft: '8px' }}
                        >
                          删除
                        </Button>
                    </div>
                    </List.Item>
                )}
                locale={{ emptyText: "暂无评论" }}
              />
          <div className="emoji">
          <EmojiSelector onEmojiSelect={handleInsertEmoji} />
        </div>
              {admin === false ?
                <>
                  <Input.TextArea
                    rows={4}
                    value={newComment}
                    onChange={(e) => setNewComment(e.target.value)}
                    placeholder={replyTo ? `回复 ${replyTo}：` : "请输入评论内容"}
                  />
                  <Button
                    type="primary"
                    onClick={handleCommentSubmit}
                    style={{ marginTop: "8px" }}
                    block
                  >
                    提交评论
                  </Button>
                  {replyTo && (
                    <div style={{ marginTop: 8, color: "#888" }}>
                      正在回复 <b>{replyTo}</b>，
                      <a onClick={() => setReplyTo(null)} style={{ marginLeft: 8 }}>
                        取消
                      </a>
                    </div>
                  )}
                </>
                :
                <></>}
            </div>
          </div>
        )}
      </Spin>
    </Modal>
  );
}

export default SeedDetail;
